package com.central.apps.controller;

import com.central.app.service.HandlerService;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = "采购管理询价单接口")
@RequestMapping("/inquirySheet")
public class InquirySheetController {
    @Autowired
    private HandlerService handlerService;
    @GetMapping("/inquirysheet")
    public Map<String,Object> inquirysheet(@RequestParam String id,@RequestParam Integer page,@RequestParam Integer limit) throws Exception{

        List<Map<String,Object>> bysql2= new ArrayList<>();
        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_inquirysheetline where isid='" + id + "'");
        if (CollectionUtils.isNotEmpty(bySql)){
            for (int i=0;i<bySql.size();i++){
                Map<String, Object> map = bySql.get(i);
                String id1 = MapUtils.getString(map, "id");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_isoffer where inquiryitemid='" + id1 + "'");
                if (CollectionUtils.isNotEmpty(bySql1)){
                    for (int j=0;j<bySql1.size();j++){
                        Map<String, Object> map1 = bySql1.get(j);
                        String itemnum = MapUtils.getString(map1, "itemnum");
                        String suppliernum = MapUtils.getString(map1, "suppliernum");
                        String id2 = MapUtils.getString(map1, "id");
                        String isnum = MapUtils.getString(map1, "isnum");
                        List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_isoffer where itemnum='" + itemnum + "' and suppliernum='" + suppliernum + "' and id not in (select id from gq_isoffer where isnum='"+isnum+"')");
                        for (int z=0;z<bySql3.size();z++){
                            Map<String, Object> map2 = bySql3.get(z);
                            bysql2.add(map2);
                        }
                    }
                }
            }
        }
        List<Map<String,Object>> collect = bysql2.stream().skip((page-1)*limit).limit(limit).collect(Collectors.toList());
        HashMap<String, Object> hashMap = new HashMap<>();
        String code="0";
        hashMap.put("count",bysql2.size());
        hashMap.put("code",code);
        hashMap.put("data",collect);
        return hashMap;
    }
    @PostMapping("/generatePO")
    public String generatePO(@RequestBody Map<String,Object> params) throws Exception {
        JSONObject json = new JSONObject();
        String isnum = MapUtils.getString(params,"isnum");
        String suppliernum = MapUtils.getString(params,"suppliernum");

        // 查询询价单报价信息
        List<Map<String, Object>> isOfferList = handlerService.findBySql("select * from gq_isoffer where (converttopo = '0' or converttopo is null) and isawared = 1 and isnum ='" + isnum + "' and suppliernum = '" + suppliernum + "'");

        if (CollectionUtils.isEmpty(isOfferList)) {
            json.put("code", "1");
            json.put("msg", "该供应商没有已中标的物资或已经生成过订单，不能生成订单");
            return json.toString();
        }

        // 查询询价单主表信息
        List<Map<String, Object>> isList = handlerService.findBySql("select * from gq_inquirysheet where isnum ='" + isnum + "'");

        if (CollectionUtils.isNotEmpty(isList)) {
            // 获取询价单信息
            Map<String, Object> isMap = isList.get(0);

            String isid = MapUtils.getString(isMap,"id");
            String description = MapUtils.getString(isMap,"description");
            String freightterms = MapUtils.getString(isMap,"freightterms");
            String shipvia = MapUtils.getString(isMap,"shipvia");
            String paymentterms = MapUtils.getString(isMap,"paymentterms");
            String closeondate = MapUtils.getString(isMap,"closeondate");
            String requestedby = MapUtils.getString(isMap,"requestedby");
            String orgcode = MapUtils.getString(isMap,"orgcode");
            String sitecode = MapUtils.getString(isMap,"sitecode");
            String deptcode = MapUtils.getString(isMap,"deptcode");
            String shipto = MapUtils.getString(isMap,"shipto");
            String billto = MapUtils.getString(isMap,"billto");
            String replytoattn = MapUtils.getString(isMap,"replytoattn");
            String reqdeptcode = MapUtils.getString(isMap,"reqdeptcode");

            // 组织采购订单信息
            Map<String, Object> map = new HashMap<>();
            map.put("description", description);
            map.put("requireddate", closeondate);
            map.put("suppliernum", suppliernum);
            map.put("freightterms", freightterms);
            map.put("shipvia", shipvia);
            map.put("paymentterms", paymentterms);

            // 生成采购订单编码
            Map<String, Object> poMap = new HashMap<>();
            handlerService.addBizNum("poApp", "gq_po", poMap);
            // 查询采购订单编码
            String ponum = (String) poMap.get("ponum");
            map.put("ponum", ponum);
            map.put("status", "新建");

            // 总公司、分公司、部门编码空值
            map.put("orgcode", orgcode);
            map.put("sitecode", sitecode);
            map.put("deptcode", deptcode);

            // 插入采购订单信息
            BigInteger poid = (BigInteger) handlerService.insert( "gq_po", map);

            List<Map<String, Object>> polineDatas = new ArrayList<>();
            float poTotalcost = 0f;
            float poTotaltax = 0f;
            float poBeforetax = 0f;
            for (Map<String, Object> isOfferMap : isOfferList) {
                int isOfferid = (int) isOfferMap.get("id");
                int islineid = (int) isOfferMap.get("islineid");
                int orderqty = (int) isOfferMap.get("orderqty");
                String orderunit = (String) isOfferMap.get("orderunit");
                float unitcost = (float) isOfferMap.get("unitcost");
                float taxrate = (float) isOfferMap.get("taxrate");
                float totalcost = (float) isOfferMap.get("totalcost");
                float linecost = (float) isOfferMap.get("linecost");
                String taxcode = (String) isOfferMap.get("taxcode");
                float taxamount = (float) isOfferMap.get("taxamount");
                float beforetax = (float) isOfferMap.get("beforetax");

                // 查询询价单子表明细
                List<Map<String, Object>> islineList = handlerService.findBySql("select * from gq_inquirysheetline where id =" + islineid);
                Map<String, Object> islineMap = islineList.get(0);
                String linetype = (String) islineMap.get("linetype");
                String serverDesc = (String) islineMap.get("description");
                String itemnum = (String) islineMap.get("itemnum");
                String itemdesc = (String) islineMap.get("itemdesc");
                String model = (String) islineMap.get("model");

                String prlinenum = (String) islineMap.get("prlinenum");
                String prnum = (String) islineMap.get("prnum");
                int prlineid = 0;
                if (null != islineMap.get("prlineid")) {
                    prlineid = (int) islineMap.get("prlineid");
                }
                Timestamp reqdeliverydate = (Timestamp) islineMap.get("reqdeliverydate");
                String islinenum = (String) islineMap.get("islinenum");

                // 组织采购订单明细数据
                Map<String, Object> polineMap = new HashMap<>();
                polineMap.put("poid", poid);
                polineMap.put("ponum", ponum);
                polineMap.put("requestedby", requestedby);
                polineMap.put("reqdeliverydate", reqdeliverydate);
                polineMap.put("reqdeptcode", reqdeptcode);

                polineMap.put("linetype", linetype);
                polineMap.put("serverDesc", serverDesc);
                polineMap.put("itemnum", itemnum);
                polineMap.put("itemdesc", itemdesc);
                polineMap.put("model", model);
                polineMap.put("orderqty", orderqty);
                polineMap.put("amounttoreceive", orderqty);
                polineMap.put("inspectreceive", orderqty);
                polineMap.put("orderunit", orderunit);
                polineMap.put("unitcost", unitcost);
                polineMap.put("linecost", linecost);
                polineMap.put("taxcode", taxcode);
                polineMap.put("taxrate", taxrate);
                polineMap.put("taxamount", taxamount);
                polineMap.put("beforetax", beforetax);
                polineMap.put("totalcost", totalcost);

                polineMap.put("prlinenum", prlinenum);
                polineMap.put("prnum", prnum);
                polineMap.put("prlineid", prlineid);

                polineMap.put("shipto", shipto);
                polineMap.put("billto", billto);
                polineMap.put("shiptoattn", replytoattn);

                polineMap.put("islineid", islineid);
                polineMap.put("isnum", isnum);
                polineMap.put("islinenum", islinenum);
                polineMap.put("isid", isid);

                polineDatas.add(polineMap);

                // 计算采购订单主信息
                poTotalcost = poTotalcost + totalcost;
                poTotaltax = poTotaltax + taxamount;
                poBeforetax = poBeforetax + beforetax;

                // 更新询价单报价信息
                handlerService.updateBySql("update gq_isoffer set converttopo = '1' where id = " + isOfferid);
            }

            // 批量插入采购订单明细
            handlerService.batchInsert("poApp","gq_poline", polineDatas);

            // 更新采购订单
            handlerService.updateBySql("update gq_po set totaltax = "+ poTotaltax + ", pretaxtotal = "
                    + poBeforetax + ", totalcost = " + poTotalcost + " where id = " + poid);
        }

        json.put("msg", "生成采购订单成功, 请到采购订单界面查询数据!");
        return json.toString();
    }

    @PostMapping("/generateContract")
    public String generateContract(@RequestBody Map<String,Object> params) throws Exception {
        JSONObject json = new JSONObject();
        String isnum = MapUtils.getString(params,"isnum");
        String suppliernum = MapUtils.getString(params,"suppliernum");

        // 查询询价单报价信息
        List<Map<String, Object>> isOfferList = handlerService.findBySql("select * from gq_isoffer where (converttocontract = '0' or converttocontract is null) and isawared = 1 and isnum ='" + isnum + "' and suppliernum = '" + suppliernum + "'");

        if (CollectionUtils.isEmpty(isOfferList)) {
            json.put("code", "1");
            json.put("msg", "该供应商没有已中标的物资或已经生成过订单，不能生成订单");
            return json.toString();
        }

        json.put("msg", "生成合同成功, 请到合同管理界面查询数据!");
        return json.toString();
    }
}
